package com.macro.mall.runner;

import com.macro.mall.dao.SmsFlashPromotionSkuRelationDao;
import com.macro.mall.model.SmsFlashPromotionSkuRelation;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author：Minxiao-Hao
 * @Description: 秒杀商品预热缓存
 * @name：GoodsFlashPreheat
 * @Date：2024/11/1 16:34
 */
@Component
public class FlashProductPreheatCache {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SmsFlashPromotionSkuRelationDao smsFlashPromotionSkuRelationDao;

    /**
     * 定义一个每天晚上22点定时器来做秒杀商品预热缓存
     */
    @Scheduled(cron = "0 0 22 * * ? ")
    public  void productHeat() {
        // 预热秒杀商品
        List<SmsFlashPromotionSkuRelation> list = smsFlashPromotionSkuRelationDao.findAll();
        for (SmsFlashPromotionSkuRelation smsFlashPromotionSkuRelation : list) {
            // 获取skuId
            Long skuId = smsFlashPromotionSkuRelation.getSkuId();
            //获取限时购id
            Long flashPromotionId = smsFlashPromotionSkuRelation.getFlashPromotionId();
            // 获取限时购场次id
            Long flashPromotionSessionId = smsFlashPromotionSkuRelation.getFlashPromotionSessionId();
            // 获取库存数量
            Integer stock = smsFlashPromotionSkuRelation.getFlashPromotionCount();
            // 预热商品库存
            if(stock!=null){
                redisTemplate.opsForValue().set(flashPromotionId+":"+flashPromotionSessionId+":"+skuId, stock.toString());
            }
        }
    }
    @PostConstruct
    @Lazy //懒加载
    public void preheat() {
        // 预热秒杀商品
        this.productHeat();
    }
}
